package com.aaa.tars.controller;

import com.aaa.tars.entity.Order;
import com.aaa.tars.entity.OrderItem;
import com.aaa.tars.entity.Visitors;
import com.aaa.tars.service.OrderService;
import com.aaa.tars.service.VisitorsService;
import com.aaa.tars.util.OrderStateEnum;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.Result;
import com.aaa.tars.util.ResultUtil;
import com.aaa.tars.vo.OrderCreateDTO;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @FileName: OrderController
 * @Description: 订单控制器，处理订单相关的HTTP请求
 * @Author: ghz
 * @CreateTime:2025/9/8 14:43
 * @Version:1.0.0
 */
@RestController
@RequestMapping("order")
@Log4j2
public class OrderController {
    /**
     * 订单服务对象，用于调用订单相关业务逻辑
     */
    @Resource
    private OrderService orderService;
    @Resource
    private VisitorsService visitorsService;


    /**
     * 分页查询订单信息
     * @param page 分页参数和查询条件
     * @return Result 统一返回结果封装
     */
    @PostMapping("queryByPage")
    public Result queryPage(@RequestBody Page<Order> page){
        return ResultUtil.success(this.orderService.queryByPage(page));
    }

    /**
     * 根据ID查询订单信息
     * @param orderId 订单ID
     * @return Result 统一返回结果封装
     */
    @GetMapping("queryById")
    public Result queryById(Integer orderId){
        return ResultUtil.success(this.orderService.queryById(orderId));
    }

    @GetMapping("queryByNo/{orderNo}")
    public Result queryByOrderNo(@PathVariable String orderNo) {
        return ResultUtil.success(orderService.queryByNo(orderNo));
    }

    /**
     * 新增订单信息
     * @param
     * @return Result 统一返回结果封装
     */
    // 新增订单：接收订单和详情列表（前端需传{"order": {...}, "orderItemList": [...]}）
    @PostMapping("insert")
// 直接用 DTO 接收，Spring 自动反序列化为实体类，无需手动转换
    public Result insert(@Valid @RequestBody OrderCreateDTO createDTO) {
        // 1. 从 DTO 中提取参数（无需类型转换，直接使用）
        Order order = createDTO.getOrder();
        List<OrderItem> orderItemList = createDTO.getOrderItemList();

        // 2. 后续校验逻辑（与方案一一致）
        Integer visitorId = order.getVisitorId();
        if (visitorId == null || visitorId <= 0) {
            return ResultUtil.error("订单缺少有效的visitorId（游客ID不能为空）");
        }
        Visitors visitor = visitorsService.queryById(visitorId);
        if (visitor == null) {
            return ResultUtil.error("游客不存在（visitorId：" + visitorId + "）");
        }

        // 3. 执行插入逻辑
        try {
            int count = orderService.insert(order, orderItemList);
            return ResultUtil.success(count);
        } catch (Exception e) {
            log.error("订单插入接口异常", e);
            return ResultUtil.error("订单创建失败：" + e.getMessage());
        }
    }


    /**
     * 更新订单信息
     * @param order 订单实体对象
     * @return Result 统一返回结果封装
     */
    @PostMapping("update")
    public Result update(@RequestBody Order order){
        return ResultUtil.success(this.orderService.update(order));
    }

    /**
     * 根据订单号更新订单状态
     * @param orderNo 订单号
     * @param orderState 目标订单状态
     * @return Result 统一返回结果封装
     */
    @PostMapping("updateStateByNo")
    public Result updateOrderStateByNo(@RequestParam String orderNo, @RequestParam String orderState) {
        try {
            // 根据状态码获取枚举值
            OrderStateEnum targetState = OrderStateEnum.fromCode(orderState);
            if (targetState == null) {
                return ResultUtil.error("无效的订单状态码: " + orderState);
            }
            
            int result = orderService.updateOrderStateByNo(orderNo, targetState);
            return ResultUtil.success(result);
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }
    
    /**
     * 根据游客ID查询订单列表
     * @param visitorId 游客ID
     * @return Result 统一返回结果封装
     */
    @PostMapping("queryByVisitorId")
    public Result queryByVisitorId(@RequestParam Integer visitorId) {
        try {
            List<Order> orders = orderService.queryByVisitorId(visitorId);
            return ResultUtil.success(orders);
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    /**
     * 根据ID删除订单信息
     * @param orderId 订单ID
     * @return Result 统一返回结果封装
     */
    @DeleteMapping("deleteById")
    public Result deleteById(Integer orderId){
        return ResultUtil.success(this.orderService.deleteById(orderId));
    }
    
    /**
     * 核销订单验证码
     * @param orderNo 订单号
     * @param verificationCode 验证码
     * @return Result 统一返回结果封装
     */
    @PostMapping("verifyTicket")
    public Result verifyTicket(@RequestParam String orderNo, @RequestParam String verificationCode) {
        try {
            boolean result = orderService.verifyTicket(orderNo, verificationCode);
            if (result) {
                return ResultUtil.success("核销成功");
            } else {
                return ResultUtil.error("核销失败，验证码不正确或订单状态异常");
            }
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }

}